package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.ThreadLocalUtils;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.ex.CustomerException;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 订单业务层实现
 */
@Service
@Transactional
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailService OrderDetailService;

    /**
     * 结算订单
     *
     * @param orders
     * @return
     */
    @Override
    public R submit(Orders orders) {
        Long addressBookId = orders.getAddressBookId();
        Integer payMethod = orders.getPayMethod();
        String remark = orders.getRemark();

        //1.获得当前用户id, 查询当前用户的购物车数据
        Long userId = ThreadLocalUtils.get();
        LambdaQueryWrapper<ShoppingCart> lqw = Wrappers.<ShoppingCart>lambdaQuery()
                .eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> carts = shoppingCartService.list(lqw);
        if (CollectionUtils.isEmpty(carts)) {
            throw new CustomerException("购物车不存在");
        }

        //2.组装订单数据

        //2.1 获取地址簿数据
        AddressBook addressBook = addressBookService.getById(addressBookId);

        //2.2 获取登录人数据
        User user = userService.getById(userId);

        LocalDateTime now = LocalDateTime.now();
        Orders myOrder = new Orders();
        long orderId = IdWorker.getId();
        myOrder.setNumber(orderId + ""); // 订单号
        myOrder.setStatus(2);   // 订单状态
        myOrder.setUserId(userId);  // 下单人ID
        myOrder.setAddressBookId(addressBookId);// 地址ID
        myOrder.setOrderTime(now);// 下单时间
        myOrder.setCheckoutTime(now);// 结账时间
        myOrder.setPayMethod(payMethod);// 支付方式
        myOrder.setRemark(remark);// 备注
        myOrder.setPhone(addressBook.getPhone());// 收货人手机号
        myOrder.setAddress(addressBook.getDetail());// 收货人地址
        myOrder.setConsignee(addressBook.getConsignee());// 收货人
        myOrder.setUserName(user.getName()); // 下单人

        //总金额
        AtomicInteger amount = new AtomicInteger();
        List<OrderDetail> details = carts.stream().map(item ->{
            // 组装订单明细数据
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item,orderDetail);
            orderDetail.setOrderId(orderId);
            // 总金额
            BigDecimal detailAmount = orderDetail.getAmount().multiply(new BigDecimal(orderDetail.getNumber()));
            amount.addAndGet(detailAmount.intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        // 设置订单总金额
        myOrder.setAmount(new BigDecimal(amount.get()));

        // 保存订单及明细
        this.save(myOrder);
        OrderDetailService.saveBatch(details);


        // 删除当前用户的购物车列表数据
        shoppingCartService.remove(lqw);

        return R.success("下单成功");
    }
}